package com.duqc.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName MyClassLoader
 * @Description MyClassLoader
 * @Author duqc
 * @Date 2022/5/11
 **/
public class MyClassLoader extends ClassLoader {
    /**
     * 需要加载类的路径
     */
    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) {
        Class<?> clazz = null;
        byte[] clazzByteArr = getData();

        if (clazzByteArr != null) {
            clazz = defineClass(name, clazzByteArr, 0, clazzByteArr.length);
        }
        return clazz;
    }

    /**
     * 获取class文件字节数组
     *
     * @return
     */
    private byte[] getData() {
        File file = new File(this.classPath);
        if (file.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(file);
                out = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int size;
                while ((size = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    Objects.requireNonNull(in).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return Objects.requireNonNull(out).toByteArray();
        } else {
            return null;
        }
    }

    public String getClassPath() {
        return classPath;
    }

    public void setClassPath(String classPath) {
        this.classPath = classPath;
    }
}
